<template>
  <div class="dashboard-container">
    <el-card shadow="never">
      <!-- navbar 搜索区域 -->
      <el-row type="flex">
        <el-col>
          <el-row type="flex" justify="space-between">
            <el-col>
              <span class="uname">目录名称</span>
              <el-input style="width: 200px" v-model="directoryName"></el-input>
            </el-col>
            <!-- 11111111111111111111 -->
            <el-col>
              <span class="uname">状态</span>
              <el-select placeholder="请选择" v-model="state">
                <el-option
                  :label="item.label"
                  v-for="item in stateList"
                  :key="item.value"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-col>
            <!-- 1111111111111111111111111 -->
            <el-col>
              <el-button @click="clearFn">清除</el-button>
              <el-button
                type="primary"
                @click="searchFn"
                :disabled="directoryName === '' && state === ''"
                >搜索</el-button
              >
            </el-col>
            <el-col class="fd">
              <span
                class="uname"
                @click="$router.push('/subjects/list')"
                v-if="$route.query.id"
                >←返回学科</span
              >
              <el-button type="success" @click="addDirectorys"
                >新增目录</el-button
              >
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <!-- 标签 -->
      <el-row>
        <div class="tips">
          <i class="el-icon-info" />
          <span>数据一共{{ total }}条</span>
        </div>
      </el-row>

      <!-- 表格部分 -->
      <div class="box">
        <template>
          <el-table :data="tableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="180">
            </el-table-column>
            <el-table-column prop="subjectName" label="所属学科" width="180">
              <template slot-scope="scope">
                {{ scope.row.subjectName }}
              </template>
            </el-table-column>
            <el-table-column prop="directoryName" label="目录名称">
            </el-table-column>
            <el-table-column prop="username" label="创建者"> </el-table-column>
            <el-table-column prop="addDate" label="创建日期">
              <template slot-scope="scope">
                {{ parseTime(scope.row.addDate) }}
              </template>
            </el-table-column>
            <el-table-column prop="totals" label="面试题数量">
            </el-table-column>
            <el-table-column prop="state" label="状态">
              <template slot-scope="scope">
                {{ getState(scope.row.state) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" prop="id">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="prohibit(scope.row)"
                >
                  <!-- {{ getState(scope.row.state) }} -->
                  {{ scope.row.state === 0 ? "点击启用" : "点击禁用" }}
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="editBtn(scope.row)"
                  :disabled="scope.row.state === 0"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="delList(scope.row)"
                  :disabled="scope.row.state === 0"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 页码  -->
          <el-pagination
            style="margin-top: 20px"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[2, 4, 6, 8, 10]"
            :page-size="pageParams.pagsize"
            layout=" sizes,prev, pager, next, jumper"
            :total="total"
            :current-page.sync="page1"
          >
          </el-pagination>
        </template>
      </div>
      <!-- 弹窗部分 -->
      <el-dialog
        @close="closeFn"
        :title="isEdit === true ? '编辑' : '新增目录'"
        :visible.sync="isShow"
        width="50%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <el-form ref="form" :rules="rules" :model="form" label-width="80px">
          <el-form-item
            label="所属学科"
            prop="subjectID"
            v-if="!$route.query.id"
          >
            <el-select
              placeholder="请选择"
              v-model="form.subjectID"
              style="width: 100%"
            >
              <el-option
                :label="item.label"
                v-for="item in subjectNames"
                :key="item.value"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录名称" prop="directoryName">
            <el-input v-model="form.directoryName"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">立即创建</el-button>
            <el-button @click="close">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// 引入数据列表 // 新增
import {
  list,
  addList,
  remove,
  detail,
  update,
  changeStateAPI
} from '@/api/hmmm/directorys'
// 引用学科简单列表
import { simple } from '@/api/hmmm/subjects'
// 引入=启用=禁用的功能
import { status } from '@/api/hmmm/constants'

// 引入时间转换函数
// 目录状态
import { parseTime } from '@/utils'
export default {
  data () {
    return {
      rules: {
        subjectID: [
          { required: true, message: '请选择所属学科', trigger: 'blur' }
        ],
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ]
      },
      directoryName: '',
      stateList: status,
      page1: 0, // 默认页数
      state: null,
      currentPage: '',
      total: 0,
      subjectNames: [], // 所有的所属学科的简单列表
      pageParams: {
        pagesize: 10, // 每页的数据数
        page: 1 // 当前页码
      },
      tableData: [], // 页面加载的数据
      editForm: {
        subjectName: '', // 所属学科
        directoryName: '', // 目录名称
        username: '', // 创建者
        addDate: '', // 创建日期
        totals: '', // 面试题数量
        state: '', // 状态
        subjectID: ''
      },
      isShow: false,
      isEditShow: false,
      isEdit: false,
      form: {
        subjectID: '',
        directoryName: ''
      },
      isSearch: false
    }
  },
  created () {
    if (!this.$route.query.id) {
      this.loadDirectorys()
    }
    this.getSimpleList()
  },
  methods: {
    // 加载数据
    async loadDirectorys () {
      this.isSearch = false
      const res = await list(this.pageParams)
      console.log('页面数据', res.data.items)
      this.total = res.data.counts
      this.tableData = res.data.items
    },

    // 转换时间格式
    parseTime (time) {
      return parseTime(time)
    },

    // 获取目录状态
    getState (id) {
      const obj = {}
      status.forEach((item) => {
        obj[item.value] = item.label
      })
      // console.log('// 获取目录状态的值', obj, obj[id])
      return obj[id]
    },

    // 手动修改当前页码
    handleCurrentChange (curPage) {
      console.log('当前页码', curPage)
      this.pageParams.page = curPage
      this.loadDirectorys()
    },

    // 更改每页显示数据几条
    handleSizeChange (size) {
      console.log('更改每页显示数据几条', size)
      this.pageParams.pagesize = size
      this.loadDirectorys()
      // this.page1 = 1
      // this.pageParams.page = 1
    },

    // 搜索功能  111111111111111111111111111111111111111111111111111111111111111111
    async searchFn () {
      this.isSearch = true
      console.log('搜索功能关键字', this.directoryName)
      const res = await list({
        directoryName: this.directoryName,
        state: this.state
      })
      this.tableData = res.data.items
      console.log('搜索功能', res)
    },

    // 获取学科简单列表数据
    async getSimpleList () {
      const res = await simple()
      this.subjectNames = res.data
      console.log('获取简单列表的数据', this.subjectNames)
    },

    // 新增目录
    addDirectorys () {
      this.isEdit = false
      this.isShow = true
    },
    // 新增
    async addDirectorysList () {
      // 如果 学科传过来的有值,则把值中的id赋值给 subjectID
      if (this.$route.query.id) {
        this.form.subjectID = Number(this.$route.query.id)
      }
      this.isEdit = false
      console.log('新增form', this.form)
      const res = await addList({ ...this.form })
      console.log('新增', res)
      this.loadDirectorys()
      this.isShow = false
    },

    // 兜底校验
    onSubmit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.isEdit ? this.hAddDirectory() : this.addDirectorysList()
        }
      })
    },

    // 删除
    delList (id) {
      this.$confirm('此操作将永久删除角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 做删除
          const res = await remove(id)
          console.log('删除的数据', res)

          // 刷新页面
          this.loadDirectorys()
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message.Error('删除失败')
        })
    },

    // 点击编辑按钮
    async editBtn (row) {
      this.isShow = true
      this.isEdit = true
      console.log(row)
      // 获取 目录详情
      const res = await detail(row)
      console.log('获取 目录详情', res)
      // 数据回填
      this.form = res.data
    },
    // 编辑事件
    async hAddDirectory () {
      try {
        const res = await update(this.form)
        console.log(res)
        this.loadDirectorys()
        this.$message.success('编辑成功')
        this.isShow = false
      } catch (error) {
        this.$message.Error('编辑失败')
      }
    },

    // 禁用
    async prohibit (row) {
      console.log('data1111111111', row.id)
      var data = {
        id: row.id,
        state: Number(!row.state)
      }
      console.log('data1111111111', data)
      await changeStateAPI(data)
      this.loadDirectorys()
    },
    // 点击××关闭窗口清空数据
    closeFn () {
      this.$refs.form.resetFields()
      this.form = {
        subjectID: '',
        directoryName: ''
      }
      this.isShow = false
    },
    close () {
      this.closeFn()
    },
    clearFn () {
      this.directoryName = ''
      this.state = ''
      this.loadDirectorys()
    }
  },
  watch: {
    '$route.query.name': {
      handler: function (newVal, oldVal) {
        console.log('handler', newVal)
        this.directoryName = newVal
        this.searchFn()
      },
      immediate: true
    }
  }
}
</script>

<style scoped lang='scss'>
.tips {
  margin: 20px 0;
  line-height: 34px;
  padding: 0px 15px;
  border-radius: 5px;
  border: 1px solid rgba(145, 213, 255, 1);
  background: #f4f4f5;
  i {
    margin-right: 10px;
    color: #909399;
  }
}
.uname {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  margin-right: 10px;
}
.sIcon {
  margin: 0 10px;
  color: #909399;
}
.num {
  font-size: 12px;
  color: #909399;
}
</style>
